package samples.java.algorithm.sort;

/**
 * @author wang.yuchuan
 * @createdAt 2018/12/9
 */
public class QuickSort {

    static void sort(int[] arr, int left, int right) {
        if (left < right) {
            int partitionIndex = partition(arr, left, right);
            sort(arr, left, partitionIndex - 1);
            sort(arr, partitionIndex + 1, right);
        }
    }

    static int partition(int[] arr, int left, int right) {
        int pivot = left, //最左侧为基准值
            index = pivot + 1;

        for (int i = index; i <= right; i++) {
            if (arr[i] < arr[pivot]) {
                swap(arr, i, index);
                index++;
            }
        }
        swap(arr, pivot, index - 1);
        return index - 1;
    }

    static void swap(int[] arr, int i, int j) {
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {3, 44, 5, 67, 4, 23, 42, 56, 78, 91, 2, 7, 9, 12, 16};

        sort(arr, 0, arr.length - 1);

        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}
